package com.zxq.demo.core.running;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zxq.demo.core.properties.JobProperties;
import com.zxq.demo.core.shutdown.ContextClosedListener;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;

/**
 * @author zw
 * @description 程序完全初始化成功后，向调度中心注册当前服务。
 * @email 2408003640@qq.com
 * @date 2025/6/14 13:13
 */
@Slf4j
@Component
public class ZxqJobApplicationRunner implements ApplicationRunner {

    @Resource
    private JobProperties  jobProperties;
    @Resource
    private Environment environment;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 组装执行器的接口地址
        String url = generatorUrl();

        try {
            String result = HttpUtil.get(url);
            if (!"Success".equals(result)) {
                throw new RuntimeException(result);
            }
            log.info("向调度中心注册, url: {}, 返回结果: {}", url, result);
        } catch (Exception e) {
            log.error("向调度中心注册失败, url: {}, 失败原因: {}", url, e.getMessage());
            throw new RuntimeException("向调度中心注册失败, adminUrl: " + url);
        }
    }

    private String generatorUrl() {
        try {
            String port = environment.getProperty("server.port");
            String contextPath = environment.getProperty("server.servlet.context-path");
            if (StringUtil.isNullOrEmpty(contextPath)) {
                contextPath = "";
            } else {
                contextPath = "/" + contextPath;
            }
            String ip = InetAddress.getLocalHost().getHostAddress();
            String executorUrl = "http://" + ip + ":" + port + contextPath + "/executeJob/executeJobById";  // 当前执行器的地址
            ContextClosedListener.destoryUrl = jobProperties.getAdminUrl() + "/destory?executorUrl=" + executorUrl;
            return jobProperties.getAdminUrl() + "/registry" + "?executorUrl=" + URLEncoder.encode(executorUrl, "UTF-8");
        } catch (UnknownHostException e) {
            log.error("获取执行器ip地址失败, 异常信息: {}", e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error("执行器地址编码失败, 异常信息: {}", e.getMessage());
        }
        return null;
    }
}
